package net.NingXiaRuiTai.ShortChain.controller;

import com.google.code.kaptcha.Producer;

import lombok.extern.slf4j.Slf4j;
import net.NingXiaRuiTai.ShortChain.controller.request.SendCodeRequest;
import net.NingXiaRuiTai.ShortChain.enums.BizCodeEnum;
import net.NingXiaRuiTai.ShortChain.enums.SendCodeEnum;
import net.NingXiaRuiTai.ShortChain.server.NotifyServer;
import net.NingXiaRuiTai.ShortChain.utils.CommonUtil;
import net.NingXiaRuiTai.ShortChain.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private NotifyServer notifyServer;

    //验证码过期时间 10分钟
    private static final Integer CAPTCHA_CODE_EXPIRED = 1000 * 60 * 10;
    @Qualifier("redisTemplate")//
    @Autowired
    private RedisTemplate redisTemplate;

    /*
     * 生成验证码
     * */
    @GetMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        //生成验证码
        String text = captchaProducer.createText();
        log.info("验证码:{}", text);
        //存储到redis，配置过期时间
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request), text, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        //生成验证码图片
        BufferedImage image = captchaProducer.createImage(text);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error("获取流出错");
        }


    }

    /*
     * 生成key，使用ip地址+系统指纹
     * */
    private String getCaptchaKey(HttpServletRequest request) {
        //使用Commonutil获取ip地址
        String ip = CommonUtil.getIpAddr(request);
        //使用系统指纹
        String userAgent = request.getHeader("User-Agent");
        //对（ip+系统指纹）使用md5加密
        String key = "account-servers:captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("验证码key:{}", key);
        return key;
    }

    /*发送短信验证码
     *
     * */
    @PostMapping("send_sms_code")
    public JsonData send_sms_code(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        String captchaKey = getCaptchaKey(request);
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(captchaKey);
        String captcha = sendCodeRequest.getCaptcha();
        if (cacheCaptcha != null && cacheCaptcha.equals(captcha)) {
            //成功
            stringRedisTemplate.delete(captchaKey);
            JsonData jsonData = notifyServer.sendCode(SendCodeEnum.USER_REGISTER, sendCodeRequest.getToPhone());
            return jsonData;
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }


    }

    @RequestMapping("send_code")
    public JsonData send_code() {

        return JsonData.buildSuccess();
    }
}
